package com.gcu.common.uikit.input

import android.content.Context
import android.graphics.Color
import android.graphics.Rect
import android.text.Editable
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.view.Gravity
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AppCompatDialog
import com.gcu.common.R
import com.gcu.common.databinding.DialogInputBinding
import com.gcu.common.utils.ToastUtil

/**
 * 自定义输入框
 * @property mContext Context
 * @property mMaxTextNumber Int
 * @property mMinTextNumber Int
 * @property mCurTextNumber Int
 * @property mLastDiff Int
 * @property mBinding DialogInputBinding
 * @property mInputMethodManager InputMethodManager
 * @property mForegroundColorSpan ForegroundColorSpan
 * @property mSpannableStringBuilder SpannableStringBuilder
 */
class InputDialog : AppCompatDialog {

    private val mContext: Context = context
    private var mMaxTextNumber = 10
    private var mMinTextNumber = 3
    private var mCurTextNumber = 0
    private var mLastDiff = 0
    private val mBinding: DialogInputBinding = DialogInputBinding.inflate(layoutInflater)
    private val mInputMethodManager: InputMethodManager
    private val mForegroundColorSpan = ForegroundColorSpan(Color.RED)
    private val mSpannableStringBuilder = SpannableStringBuilder()

    constructor(context: Context, theme: Int = R.style.dialog) : super(context, theme) {
        setContentView(mBinding.root)
        mInputMethodManager =
            mContext.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        init()
        setLayout()
    }

    private fun init() {
        mBinding.tvCount.text = context.getString(
            R.string.edit_count_text,
            mCurTextNumber.toString(),
            mMaxTextNumber.toString()
        )
        mBinding.etInput.requestFocus()
        mBinding.etInput.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence, p1: Int, p2: Int, p3: Int) {

            }

            override fun afterTextChanged(editable: Editable) {
                if (editable.length > mMaxTextNumber) {
                    val overString = (mMaxTextNumber - editable.length).toString()
                    mBinding.tvCount.text = context.getString(
                        R.string.edit_count_text,
                        overString,
                        mMaxTextNumber.toString()
                    )
                    setInterceptCountTextColor(overString, mBinding.tvCount.text.toString())
                } else {
                    mBinding.tvCount.text = context.getString(
                        R.string.edit_count_text,
                        editable.length.toString(),
                        mMaxTextNumber.toString()
                    )
                }
            }
        })
        mBinding.tvPublish.setOnClickListener {
            handlePublish()
        }
        mBinding.root.addOnLayoutChangeListener { view, i, i2, i3, i4, i5, i6, i7, i8 ->
            val rect = Rect()
            window?.decorView?.getWindowVisibleDisplayFrame(rect)
            val screenHeight = window?.decorView?.rootView?.height
            val heightDifference = screenHeight?.minus(rect.bottom)
            if (heightDifference != null) {
                if (heightDifference <= 0 && mLastDiff > 0) {
                    dismiss()
                }
                mLastDiff = heightDifference
            }
        }
    }

    private fun handlePublish() {
        if (mBinding.etInput.text.length < mMinTextNumber) {
            ToastUtil.toastShortMessage(context, "字数小于${mMinTextNumber}噢~")
            return
        }
        if (mBinding.etInput.text.length > mMaxTextNumber) {
            ToastUtil.toastShortMessage(context, "字数大于${mMinTextNumber}噢~")
            return
        }
    }

    private fun setLayout() {
        val layoutParams = window?.attributes
        layoutParams?.run {
            width = WindowManager.LayoutParams.MATCH_PARENT
            height = WindowManager.LayoutParams.WRAP_CONTENT
        }
        window?.run {
            setGravity(Gravity.BOTTOM)
            attributes = layoutParams
            setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
        }
        setCancelable(true)
    }

    private fun setInterceptCountTextColor(changeWord: String, content: String) {
        if (changeWord.isEmpty() || content.isEmpty()) return
        if (!content.contains(changeWord)) return
        val start = 0
        val end = changeWord.length
        if (start != end) {
            mSpannableStringBuilder.clear()
            mSpannableStringBuilder.append(content)
            mSpannableStringBuilder.setSpan(
                mForegroundColorSpan,
                start,
                end,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
            )
            mBinding.tvCount.text = mSpannableStringBuilder
        }
    }

    fun setMaxNumber(num: Int) {
        mMaxTextNumber = num
        mBinding.tvCount.text = context.getString(
            R.string.edit_count_text,
            mCurTextNumber.toString(),
            mMaxTextNumber.toString()
        )
    }

    fun setHint(hint: String) {
        mBinding.etInput.hint = hint
    }

    override fun dismiss() {
        super.dismiss()
        mLastDiff = 0
    }

    override fun show() {
        super.show()
    }
}